﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Services.Gateway.Runtime;
using PServiceBus.Transports;
using PServiceBus.Core.Runtime.Transports;
using System.Diagnostics;
using System.IO;

namespace Resequencer {
    public class Resequence {
        public int ID { get; set; }
        public static Resequence New(int id) {
            return new Resequence { ID = id };
        }
    }
    class Program {
        static void Main(string[] args) {
            ESB.Authenticate("rpgmaker", "password1");

           
            Topic.RegisterIfNotExist<Resequence>();

            var subscriber = Subscriber.New("ResequenceSubscriber").Durable(false)
                .SubscribeTo(Topic.Select<Resequence>())
                 .AddTransportFor<Resequence>("Tcp", Transport.New<TcpTransport>(
                    transport =>
                    {
                        transport.Format = TransportFormat.Xml; 
                        transport.IPAddress = "127.0.0.1";
                        transport.Port = 8888;
                    }))
                ;

            subscriber.Save();


            subscriber.OnMessageReceived<Resequence>("Tcp",
            msg => Console.WriteLine("Received Messaged with ID: {0}", msg.ID),
            interval: TimeSpan.FromMilliseconds(1),
            errorAction: h =>
            {
                h.Continue = true;
                Console.WriteLine(h.Error.ToString());
            });

            Console.WriteLine("Waiting for sequenced messages. Press enter to exit");

            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            var file = new FileInfo("../../../Resequencer.Server/bin/Debug/Resequencer.Server.exe");
            Process.Start(file.FullName);

            Console.ReadLine();

            subscriber.Delete();
            TransportHandlers.ShutDown();
        }
    }
}
